<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Category extends Model
{
    use SoftDeletes;
    protected $fillable = [
        'category_id', 'title', 'icon', 'banner', 'description', 'settings', 'cache',
        'slug', 'cache->articles_count', 'cache->subscribers_count',
    ];

    protected $casts = [
        'id' => 'int',
        'category_id' => 'int',
        'settings' => 'json',
        'cache' => 'json',
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function children()
    {
        return $this->hasMany(self::class);
    }

    public function parent()
    {
        return $this->belongsTo(self::class);
    }

    public function scopeRoot($query)
    {
        return $query->whereNull('category_id');
    }

    public function scopeLeaf($query)
    {
        return $query->whereNotNull('category_id');
    }

    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

    public function wikis()
    {
        return $this->belongsToMany(Wiki::class);
    }

    public function refreshCache()
    {
        $this->update([
            'cache->wikis_count' => $this->wikis()->count(),
        ]);
    }

}
